package com.qc.servicemsm.controller;


import com.qc.commonutils.result.R;
import com.qc.servicemsm.service.MsmService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Api("阿里云短信业务")
@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone){
        //1.从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2.如果redis获取不到，阿里云发送
        //生成随机值，传到aliyun进行发送
        code = String.valueOf(new Random().nextInt(1000000));
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //使用service调用发送短信的方法
        boolean flag = msmService.send(param,phone);
        if (flag){
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error().message("短信发送失败");

    }

}
